﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive;
using System.Reactive.Disposables;
using System.Reactive.Linq;
using System.Reactive.Subjects;
using System.Text;
using System.Threading.Tasks;

namespace SimpleReactiveObjects
{
    /// <summary>
    /// Provides a set of static methods for <see cref="ReactiveMessenger{T}"/>.
    /// </summary>
    public static class ReactiveMessenger
    {
        /// <summary>
        /// Converts an observable sequence to <see cref="ReactiveMessenger{T}"/>.
        /// </summary>
        /// <typeparam name="T">The type of message object.</typeparam>
        /// <param name="source">An observable sequence to convert to an messenger.</param>
        /// <returns>The messenger that forwards messages.</returns>
        public static ReactiveMessenger<T> ToReactiveMessenger<T>(this IObservable<T> source)
        {
            var ret = new ReactiveMessenger<T>(source);
            return ret;
        }
    }

    /// <summary>
    /// The default implementation of <see cref="IReactiveMessenger{T}" />.
    /// </summary>
    /// <typeparam name="T">The type of message object.</typeparam>
    public class ReactiveMessenger<T> : IReactiveMessenger<T>
    {
        private readonly IObservable<T> source;
        private readonly Subject<T> subject;
        private readonly CompositeDisposable subscriptions;

        /// <summary>
        /// Initializes a new instance of the ReactiveMessenger&lt;T&gt; class.
        /// </summary>
        public ReactiveMessenger()
            : this(Observable.Never<T>())
        {
        }

        /// <summary>
        /// Initializes a new instance of the ReactiveMessenger&lt;T&gt; class with the specified observable sequence.
        /// </summary>
        /// <param name="source">
        /// The message source.
        /// </param>
        public ReactiveMessenger(IObservable<T> source)
        {
            if (source == null)
            {
                throw new ArgumentNullException("source");
            }

            this.source = source;
            this.subject = new Subject<T>();

            this.subscriptions = new CompositeDisposable()
            {
                source.Subscribe(x => Raise(x)),
                subject,
            };
        }

        public void Raise(T message)
        {
            subscriptions.ThrowIfDisposed();

            subject.OnNext(message);
        }

        public IDisposable Subscribe(IObserver<T> observer)
        {
            subscriptions.ThrowIfDisposed();

            var ret = subject.Subscribe(observer);
            return ret;
        }

        public void Dispose()
        {
            subscriptions.Dispose();
        }
    }
}
